//
//  BundleTool.m
//  AppShellTool
//
//  Created by IOS01 on 2022/12/7.
//  处理bundle文件的工具

#import "BundleTool.h"

//存放外壳文件的目录
#define kShellBundleFolderName   @"shell"
//存放路由目录的文件
#define kRouterBundleName     @"bundle.json"

#define kSandBoxDocDir   [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
#define kShellFolderPath   [NSString stringWithFormat:@"%@/%@",kSandBoxDocDir,kShellBundleFolderName]

@implementation BundleTool


/// 将路由的文件保存到沙盒
+ (void)saveBundleJson{
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"bundle" ofType:@"json"];
    if (!bundlePath) {
        NSLog(@"路由文件不存在，请检查");
        return;
    }
    NSData *data = [NSData dataWithContentsOfFile:bundlePath];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:kShellFolderPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:kShellFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",kShellFolderPath,kRouterBundleName];
    BOOL b = [data writeToFile:filePath atomically:YES];
    if (!b) {
        NSLog(@"文件保存失败");
    }
}

+ (NSDictionary *)loadBundleJson{
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",kShellFolderPath,kRouterBundleName];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if (data) {
        NSError *err = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
        return dict;
    }
    return nil;
}

@end
